<template>
    <h1>购物车</h1>

    <button @click="addGoodsFlag = true">添加商品</button>

    <showmsg v-if="addGoodsFlag" @cancelBtn="cancelAddBtn" @okBtn="okAddBtn" />

    <!-- 商品列表 -->
    <ul class="list_ul">
        <!-- <li v-for="(item, index) in $store.state.list" :key="index"> -->
        <li v-for="(item, index) in list" :key="index">
            商品名: {{ item.name }} --- 商品价格: {{ item.price }} ---
            <button>编辑</button> ---
            <button>删除</button>
        </li>
    </ul>
</template>

<script>
import goods from "./goods";
import showmsg from "./components/showmsg.vue";
import { mapMutations, mapState } from "vuex";
export default {
    data() {
        return {
            addGoodsFlag: false,
        };
    },
    methods: {
        ...mapMutations(["setList"]),

        // 3. 获取商品
        async getGoods() {
            const list = await goods.getGoods();

            // 将数据存储到 vuex 中
            // this.$store.commit('setList', list)
            this.setList(list);
        },

        // 2. 添加弹窗的确定按钮
        async okAddBtn(formData) {
            // 2.1 将数据添加到 goods.js 中
            await goods.createGoods(formData);

            // 2.2 关闭弹窗
            this.addGoodsFlag = false;

            // 2.3 获取最新的数据
            this.getGoods()
        },

        // 1. 添加弹框的取消按钮
        cancelAddBtn() {
            this.addGoodsFlag = false;
        },
    },
    mounted() {
        this.getGoods();
    },
    computed: {
        ...mapState(['list'])
    },
    components: {
        showmsg,
    },
};
</script>

<style>
* {
    padding: 0;
    margin: 0;
}
html,
body,
#app {
    width: 100%;
    height: 100%;
}
</style>
